use crate::model::satori::SatoriMessage;
use crate::model::sys_user::SysUser;
use crate::ws::{AppState, SenderData};
use axum::extract::ws::Message;
use futures_util::SinkExt;
use serde_json::json;
use std::clone::Clone;
use tokio::sync::mpsc::Receiver;
use uuid::Uuid;
use void_log::{log_info, log_msg};

impl AppState {
    pub async fn send_task(self, mut sender_rx: Receiver<SenderData>) {
        while let Some(message) = sender_rx.recv().await {
            log_info!("Sender received: {:?}", message);

            if message.to_user.eq("all") {
                log_msg!("Sending all messages...");
                // 全体广播
                for mut client in self.clients.iter_mut() {
                    client.send(Message::Text(json!(message.satori_message).to_string())).await.expect("Send all failed");
                };
            } else if message.to_user.starts_with("private:") {
                let to_user = message.to_user.trim_start_matches("private:");
                if let Ok(user) = SysUser::select_account_code(&self.pool, to_user).await {
                    log_msg!("Sending message: {}", &message.to_user);
                    self.clone().sender_user(&user.id.unwrap(), message.satori_message.clone()).await;
                };
            } else {
                log_msg!("Sending group messages...");
                let uuid = Uuid::parse_str(&message.to_user).unwrap_or_default();
                if let Ok(users) = SysUser::select_group_id(&self.pool, &uuid).await {
                    for user in users {
                        let userid = user.id.unwrap();
                        log_info!("User Token: {}", &userid);
                        self.clone().sender_user(&userid, message.satori_message.clone()).await;
                    };
                };
            }
        }
    }

    // 发送给用户
    async fn sender_user(&self, userid: &Uuid, satori_message: SatoriMessage) {
        if let Some(mut sender) = self.clients.get_mut(userid) {
            sender.send(Message::Text(json!(satori_message).to_string())).await.unwrap();
        }
    }
}